import { checkStatus } from "./checkStatus";
import { getBaseUrl } from "../../utils/env";
import Cache from "@/utils/cache";
import { LOGIN_STATUS, LOGIN_BUSIN_STATUS } from "@/config/cache.js";
import { toLogin, weChatLogin } from "@/libs/login.js";

// import { silenceAuth } from "@/api/public";
// import Routine from "@/libs/routine";
const baseURL = getBaseUrl();

// 拦截器配置
const httpInterceptor = {
  // 拦截前触发
  invoke(options: UniApp.RequestOptions) {
    // 1. 非 http 开头需拼接地址
    if (!options.url.startsWith("http")) {
      options.url = baseURL + options.url;
    }
    // 2. 请求超时
    options.timeout = 10000;
    // 3. 添加小程序端请求头标识
    options.header = {
      "api-name": "wechat",
      ...options.header,
    };
    // 添加 urltype 请求头标识
    if (Cache.get("urltype")) {
      options.header["api-urltype"] = Cache.get("urltype");
    }
    // 添加 token 请求头标识

    const token = Cache.get(LOGIN_STATUS); //微信公众号 普通用户tokne
    const busin_token = Cache.get(LOGIN_BUSIN_STATUS); //账号密码登录企业用户tokne

    if (token) {
      options.header["api-token"] = token;
    }
    if (busin_token && !Cache.get("urltype")) {
      options.header["api-busin-token"] = busin_token;
    }
  },
};

// 拦截 request 请求
uni.addInterceptor("request", httpInterceptor);
// 拦截 uploadFile 文件上传
uni.addInterceptor("uploadFile", httpInterceptor);

/**
 * 请求函数
 * @param  UniApp.RequestOptions
 * @returns Promise
 */
type Data<T> = {
  code: number;
  msg: string;
  data: T;
  extras: string | null;
  timestamp: number;
  succeeded?: boolean;
  [name: string]: any;
};
// 2.2 添加类型，支持泛型
const http = <T>(options: UniApp.RequestOptions) => {
  // 1. 返回 Promise 对象
  return new Promise<Data<T>>((resolve, reject) => {
    uni.request({
      ...options,
      // 响应成功
      success(res: any) {
        // uni.hideLoading();
        const data = res.data;
        const code = res.data.code; //状态码

        // 状态码 2xx
        if (code > 0 && code < 300) {
          // 2.1 提取核心数据 res.data

          resolve(data as Data<T>);
        } else if (code === 401) {
          // 微信公众号 普通用户tokne
          weChatLogin();
          reject(data);
        } else if (code === 4011) {
          // 账号密码登录企业用户tokne
          toLogin();
          reject(data);
        } else {
          // 其他错误 -> 根据后端错误信息轻提示
          uni.showToast({
            icon: "none",
            title: (data as Data<T>).info || checkStatus(code),
          });
          console.log("响应失败执行showtast");

          reject(data);
        }
      },
      // 响应失败
      fail(err) {
        uni.showLoading({
          title: "网络开小差了",
        });
        setTimeout(() => {
          uni.hideLoading();
        }, 1000);
        reject(err);
      },
    });
  });
};
export default http;
